package com.flight.trans.activity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.flight.trans.R;
import com.flight.trans.adapter.LeavePortDuplicateDetailsAdapter;
import com.flight.trans.bean.ChannelBean.ChannelData;
import com.flight.trans.bean.LeavePortDuplicateBean.LeavePortDuplicateData;
import com.flight.trans.bean.LeavePortDuplicateDetailBean.DuplicateDetailData;
import com.flight.trans.bean.WeighSectionBean.WeighSectionData;
import com.flight.trans.global.Constant;
import com.flight.trans.global.ConstantInfo;
import com.flight.trans.http.NetworkUtils;
import com.flight.trans.http.network.OkGoBackListener;
import com.flight.trans.listener.OnTextClickListener;
import com.flight.trans.util.CommonUtils;
import com.flight.trans.util.JsonUtils;
import com.flight.trans.util.LogUtils;
import com.flight.trans.util.ToastUtils;
import com.flight.trans.view.dialog.AlertDialog;
import com.flight.trans.view.dialog.ChanelDialog;
import com.flight.trans.view.edit.EditorActivity;
import com.flight.trans.base.BaseActivity;
import com.google.gson.JsonObject;
import com.lzy.okgo.model.HttpParams;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 出港复重
 */
public class LeavePortDuplicateDetailsActivity extends BaseActivity implements View.OnClickListener {

    private LinearLayout mLlContainer ;
    private LinearLayout mLlTitleContainer ;
    private TextView mTvTitleName ,//标题
            mTvFlightNo ,//航班号
            mTvETD ,//预起时间
            mTvDeep ;//目的站
    private LinearLayout mLlWeighbridgeRoute ;
    private TextView mTvWeighbridgeRoute ;
    private RecyclerView mRvContainer ;

    private Button mBtnSubmit ,//提交
            mBtnRevise ,//修改
            mBtnSave ;//保存

    private ChannelData mChannelData ;
    private List<ChannelData> mChannelDataList ;

    private LeavePortDuplicateDetailsAdapter mDuplicateAdapter ;
    private List<DuplicateDetailData> mDuplicateDetailDataList;

    private LeavePortDuplicateData mLeavePortDuplicateData ;

    @Override
    public int setContentView() {
        return R.layout.activity_leave_port_duplicate_details;
    }

    @Override
    public void initView() {
        mLlContainer = findViewById(R.id.mLlContainer);
        mLlTitleContainer = findViewById(R.id.mLlTitleContainer);
        mLlWeighbridgeRoute = findViewById(R.id.mLlWeighbridgeRoute);
        mTvWeighbridgeRoute = findViewById(R.id.mTvWeighbridgeRoute);
        mTvTitleName = findViewById(R.id.mTvTitleName);
        mTvFlightNo = findViewById(R.id.mTvFlightNo);//航班号
        mTvDeep = findViewById(R.id.mTvDeep);//目的站
        mTvETD = findViewById(R.id.mTvETD);

        mBtnSubmit = findViewById(R.id.mBtnSubmit);
        mBtnRevise = findViewById(R.id.mBtnRevise);
        mBtnSave = findViewById(R.id.mBtnSave);

        mRvContainer = findViewById(R.id.mRvContainer);
    }

    @Override
    public void initData() {
        mLeavePortDuplicateData = (LeavePortDuplicateData) mBundle.getSerializable(Constant.INFO);
        IsEditor = mBundle.getBoolean(Constant.IsEditor);

        mTvFlightNo.setText(mLeavePortDuplicateData.getFlightNo());//航班号
        mTvDeep.setText(mLeavePortDuplicateData.getDeap());//目的站
        mTvETD.setText(CommonUtils.getTimeNorm(mLeavePortDuplicateData.getEtd()));


        CommonUtils.setScreenContainerPaddingTop(mLlContainer);
        CommonUtils.setScreenViewVisible(mLlTitleContainer);

        mTvTitleName.setText(getString(R.string.title_leave_port_duplicate));
        CommonUtils.onFinishTouch(mActivity , mLlContainer);
    }

    @Override
    public void initConnect() {
        valueParams = new HttpParams();
        valueParams.put(Constant.ID , mLeavePortDuplicateData.getId());
        valueParams.put(Constant.FlightID , mLeavePortDuplicateData.getFlightId());
        valueParams.put(Constant.Deap , mLeavePortDuplicateData.getDeap());

        NetworkUtils.getLeavePortDuplicateDetails(new OkGoBackListener(mActivity) {
            @Override
            public void onSuccess(Object body) {
                mDuplicateDetailDataList = (List<DuplicateDetailData>) body;

                if(mDuplicateDetailDataList == null)
                    mDuplicateDetailDataList = new ArrayList<>();

                for (int i = 0; i < mDuplicateDetailDataList.size(); i++) {
                    mDuplicateDetailDataList.get(i).setDifferenceWeight(mDuplicateDetailDataList.get(i).getDifferenceWeight() == 0 ? mDuplicateDetailDataList.get(i).getGrossWeight() : mDuplicateDetailDataList.get(i).getDifferenceWeight());
                }

                initAdapter();
            }
        }, valueParams);

        NetworkUtils.getCheckChannel(new OkGoBackListener(mActivity) {
            @Override
            public void onSuccess(Object body) {
                mChannelDataList = (List<ChannelData>) body;

                if(mChannelDataList != null && mChannelDataList.size() != 0){
                    mChannelData = mChannelDataList.get(0);
                    mTvWeighbridgeRoute.setText(mChannelData.getCode());
                }
            }
        }, Constant.LeavePortDuplicate);
    }

    private void initAdapter(){
        mBtnSubmit.setVisibility(IsEditor ? View.VISIBLE : View.GONE);
        mBtnSave.setVisibility(IsEditor ? View.VISIBLE : View.GONE);
        mLlWeighbridgeRoute.setVisibility(IsEditor ? View.VISIBLE : View.GONE);
        mBtnRevise.setVisibility(IsEditor ? View.GONE : View.VISIBLE);

        if(mDuplicateAdapter == null) {
            mDuplicateAdapter = new LeavePortDuplicateDetailsAdapter(mActivity, mDuplicateDetailDataList , IsEditor);
            mRvContainer.setAdapter(mDuplicateAdapter);
            mDuplicateAdapter.setOnTextClickListener(new TextClickListener());
            mRvContainer.setLayoutManager(new LinearLayoutManager(mActivity , RecyclerView.HORIZONTAL , false));
        }else {
            mDuplicateAdapter.updateAdapter(mDuplicateDetailDataList , IsEditor);
        }
    }

    /**
     * 条目字段点击事件
     */
    private class TextClickListener implements OnTextClickListener {
        @Override
        public void onClick(View view, int position) {
            switch (view.getId()){
                case R.id.mTvDuplicateWeight :
                    double duplicateWeight = mDuplicateDetailDataList.get(position).getDifferenceWeight() != 0 ?
                            mDuplicateDetailDataList.get(position).getDifferenceWeight() : mDuplicateDetailDataList.get(position).getGrossWeight();

                    EditorActivity.openActivity(mActivity, new EditorActivity.EditorCallbackListener() {
                        @Override
                        public void onSubmit(String content) {
                            mDuplicateDetailDataList.get(position).setDifferenceWeight(TextUtils.isEmpty(content) ? 0 : Double.parseDouble(content));

                            initAdapter();
                        }
                    } , String.valueOf(duplicateWeight));
                    break;
                case R.id.mLlRefreshTransportWeight:
                    // 刷新斗重
                    JSONObject valueObject = new JSONObject();
                    try {
                        valueObject.put(Constant.ID , mDuplicateDetailDataList.get(position).getId());
                        valueObject.put(Constant.Key_Transport_Code , mDuplicateDetailDataList.get(position).getTransportCode());
                        valueObject.put(Constant.Key_Transport_Type , mDuplicateDetailDataList.get(position).getTransportType());

                        if(mDuplicateDetailDataList.get(position).getTransportType() == 3){
                            EditorActivity.openActivity(mActivity, new EditorActivity.EditorCallbackListener() {
                                @Override
                                public void onSubmit(String content) {
                                    try {
                                        valueObject.put(Constant.Key_Transport_Weight , Double.parseDouble(content));
                                        initTransportWeight(position , valueObject.toString());
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            },String.valueOf(mDuplicateDetailDataList.get(position).getTransportWeight()) , true);
                        }else {
                            initTransportWeight(position , valueObject.toString());
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case R.id.mIbBridgeWeigh :
                    // 按钮
                    if(mChannelData == null){
                        ToastUtils.showToast(R.string.toast_weighbridge_route_null);
                        return;
                    }

                    NetworkUtils.getBridgeWeigh(new OkGoBackListener(mActivity) {
                        @Override
                        public void onSuccess(Object body) {
                            mDuplicateDetailDataList.get(position).setDifferenceWeight(Double.parseDouble(body.toString()));

                            initAdapter();
                        }
                    }, mChannelData.getCode());
                    break;
            }
        }
    }

    private void initTransportWeight(int position , String value){
        NetworkUtils.geTransportWeight(new OkGoBackListener(mActivity) {
            @Override
            public void onSuccess(Object body) {
                if(mDuplicateDetailDataList.get(position).getTransportWeight() != (Double)body){
                    mDuplicateDetailDataList.get(position).setTransportWeight((Double)body);
                    initAdapter();
                }
            }
        }, value);
    }

    @Override
    public void onClick(View v) {
        if(CommonUtils.isFastDoubleClick())
            return;

        switch (v.getId()){
            case R.id.mIbBack:
                // 返回
                onBackPressed();
                break;
            case R.id.mTvWeighbridgeRoute:
                // 选择地磅通道
                if(mDuplicateDetailDataList == null){
                    ToastUtils.showToast(R.string.toast_storeroom_inventory_data_null);
                    return;
                }

                ChanelDialog.getInstance(mActivity)
                        .setChannelData(mChannelDataList)
                        .getChannelData(Constant.LeavePortDuplicate)
                        .setOnItemClickListener(new ChanelDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(ChannelData channelData) {
                                mChannelData = channelData ;
                                mTvWeighbridgeRoute.setText(mChannelData.getCode());
                            }
                        }).show();
                break;
            case R.id.mBtnSubmit:
                // 提交
                if(mDuplicateDetailDataList == null){
                    ToastUtils.showToast(R.string.toast_storeroom_inventory_data_null);
                    return;
                }

                for (int i = 0; i < mDuplicateDetailDataList.size(); i++) {
                    DuplicateDetailData detailData = mDuplicateDetailDataList.get(i);
                    if(CommonUtils.getErrorRoute(detailData.getDifferenceWeight() , detailData.getTransportWeight() + detailData.getPalletWeight(), detailData.getWeight()).isError()){
                        ToastUtils.showToast(R.string.toast_error_route_error);
                        return;
                    }
                }

                if(IsSaveIng){
                    ToastUtils.showToast(R.string.toast_save_ing);
                    return;
                }

                AlertDialog.getInstance(mActivity)
                        .setContent(R.string.dialog_confirm_submit_duplicate_info)
                        .setConfirmButton(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                clickSubmit(true);
                            }
                        }).show();
                break;
            case R.id.mBtnSave:
                // 保存
                if(mDuplicateDetailDataList == null){
                    ToastUtils.showToast(R.string.toast_storeroom_inventory_data_null);
                    return;
                }

                if(IsSaveIng){
                    ToastUtils.showToast(R.string.toast_save_ing);
                    return;
                }

                AlertDialog.getInstance(mActivity)
                        .setContent(R.string.dialog_confirm_save_duplicate_info)
                        .setConfirmButton(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                clickSubmit(false);
                            }
                        }).show();
                break;
            case R.id.mBtnRevise:
                // 修改
                IsEditor = true ;
                initAdapter();
                break;
        }
    }

    /**
     * 提交保存
     */
    private void clickSubmit(boolean isSave) {
        if(mDuplicateDetailDataList == null)
            return;

        for (int i = 0; i < mDuplicateDetailDataList.size(); i++) {
            mDuplicateDetailDataList.get(i).setSave(isSave);
        }

        IsSaveIng = true;
        NetworkUtils.saveLeavePortDuplicateDetails(new OkGoBackListener(mActivity) {
            @Override
            public void onSuccess(Object body) {
                IsSaveIng = false;
                ToastUtils.showToast(isSave ? R.string.toast_submit_success : R.string.toast_save_success);
                onFinish(Constant.RESULT_CODE);
            }

            @Override
            public void onError() {
                IsSaveIng = false;
            }
        }, JsonUtils.parseBeanToJson(mDuplicateDetailDataList));
    }

    @Override
    protected void initRefresh(int count) {
        super.initRefresh(count);

        NetworkUtils.checkPageLock(new OkGoBackListener(mActivity) , ConstantInfo.OUT_STORAGE_OUT , mLeavePortDuplicateData.getFlightId());
    }
}
